import 'dart:convert';
import 'dart:io';

import 'package:demo/app/global.dart';
import 'package:demo/app/routes/app_pages.dart';
import 'package:dio/dio.dart';
import 'package:dio/src/multipart_file.dart' as M;
import 'package:dio/src/form_data.dart' as F;
import 'package:dio/io.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:get/get.dart';

import '../model/api_response.dart';
import '../utils/sp_util.dart';


class ApiProvider {

  static String login = '/api/login';
  static String login_code = '/api/login/code';
  static String product_list = '/api/product/list';
  static String product_click = '/api/product/pick/updated';// 点击贷超产品
  static String feedback = '/api/person/feedback/updated';// 意见反馈
  static String cancel = '/api/person/status/updated';// 注销
  static String constant = '/api/constant/item';// 获取常量
  static String identity = '/api/person/identity/detail';// 获取身份证信息
  static String loan_updated = '/api/person/loan/updated';// 贷款申请
  static String loan_list = '/api/person/loan/list/page';// 订单列表
  static String loan_detail = '/api/person/loan/detail';// 贷款详情
  static String person_detail = '/api/person/detail';// 用户详情
  static String person_updated = '/api/person/updated';// 用户信息变更
  static String job_detail = '/api/person/job/detail';// 工作详情
  static String job_updated = '/api/person/job/updated';// 工作信息变更
  static String contact_detail = '/api/person/contact/detail';// 联系人详情
  static String contact_updated = '/api/person/contact/updated';// 变更联系人
  static String province = '/api/province/item';// 省市
  static String area = '/api/area/item';// 县
  static String form_item = '/api/form/item';// 表单配置项
  static String person_save = '/api/person/save';// 用户表单变更接口
  static String api_person= '/api/person';// 用户表单详情
  static String api_check= '/api/apiproduct/check';//【api产品】撞库接口
  static String api_usable= '/api/apiproduct/usable';//【api产品】可用进件接口
  static String api_enter= '/api/apiproduct/enter';//【api产品】进件接口
  static String updated_identity= '/api/person/identity/updated';// 保存身份证及人脸照片
  static String app_online= '/api/app/online';// 是否在审核

  Dio? _dio;
  Dio getDio(){
    if(_dio == null){
      _dio = Dio();

      var isTestUrl = SpUtil.read(SpUtil.IS_TEST_URL, false);
      if(isTestUrl){
        _dio!.options.baseUrl = Global.baseUrlTest;
      }else{
        _dio!.options.baseUrl = Global.baseUrl;
      }

      _dio!.interceptors.add(InterceptorsWrapper(
        onRequest: (options, handler) {
          var token = SpUtil.read(SpUtil.TOKEN, '');
          if('$token'.isNotEmpty){
            options.headers['token'] = '$token';
          }
          print('token --> $token');

          print('\n|-------------------------------------------------------------------------------------------------');
          print('|请求地址  --> ${options.baseUrl}${options.path}');
          String jsonString = json.encode(options.headers);
          print('|请求head --> $jsonString');
          print('|请求参数  --> ${options.data}');
          print('|-------------------------------------------------------------------------------------------------\n');

          return handler.next(options);
        },
        onResponse: (response, handler) {
          print('\n|*************************************************************************************************');
          print('|请求地址  --> ${response.realUri}');
          print('|返回数据  --> ${response.data}');
          print('|*************************************************************************************************\n');
          return handler.next(response);
        },
        onError: (DioException e, handler) {
          print('\n|*************************************************************************************************');
          print('网络请求异常');
          print(e.message);
          print('|*************************************************************************************************\n');
          return handler.next(e);
        },
      ));

      var isOpenProxy = SpUtil.read(SpUtil.IS_OPEN_PROXY,false);
      var host = SpUtil.read(SpUtil.PROXY_HOST,'');
      var port = SpUtil.read(SpUtil.PROXY_PORT,'');
      if(isOpenProxy && '$host'.isNotEmpty && '$port'.isNotEmpty){
        (_dio!.httpClientAdapter as DefaultHttpClientAdapter).onHttpClientCreate = (client) {
          client.badCertificateCallback = (cert, host, port) => true;
          client.findProxy = (uri) => 'PROXY $host:$port';
          return null;
        };
      }
    }
    return _dio!;
  }


  Future<ApiResponse> getData(Map<String, dynamic> map,String url) async {
    String jsonString = json.encode(map);
    var netParams = SpUtil.read(SpUtil.NET_PARAMS,'');

    final response = await getDio().post('$url$netParams',data: jsonString);
    var result = ApiResponse.fromJson(response.data);
    if(result.code == 405 || result.code == 406){
      Get.offAllNamed(Routes.LOGIN);
      EasyLoading.showToast('${result.msg}');
    }else{
    }
    return ApiResponse.fromJson(response.data);
  }

  /// 身份证
  Future<ApiResponse> uploadImg(File file) async {
    final form = F.FormData.fromMap({
      'file': await M.MultipartFile.fromFile(file.path, filename: 'id_card.png'),
      'file_path':'identity',
      'type_id':'1'
    });
    var netParams = SpUtil.read(SpUtil.NET_PARAMS,'');

    final response = await getDio().post('/api/upload$netParams',data:form);
    return ApiResponse.fromJson(response.data);
  }

  /// 人脸照片
  Future<ApiResponse> uploadFaceImg(File file) async {
    final form = F.FormData.fromMap({
      'file': await M.MultipartFile.fromFile(file.path, filename: 'face.png'),
      'file_path':'face',
      'type_id':'2'
    });
    var netParams = SpUtil.read(SpUtil.NET_PARAMS,'');

    final response = await getDio().post('/api/upload$netParams',data:form);
    return ApiResponse.fromJson(response.data);
  }
}
